package com.liyao.windowtest4.controller;

import com.liyao.windowtest4.controller.wrench.createWrenchController;
import com.liyao.windowtest4.controller.wrench.updateWrenchController;
import com.liyao.windowtest4.pojo.Routine;
import com.liyao.windowtest4.pojo.wrenchRow;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.fxml.Initializable;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.scene.layout.AnchorPane;
import javafx.scene.layout.HBox;
import javafx.scene.layout.VBox;
import javafx.scene.text.Font;
import javafx.stage.Modality;
import javafx.stage.Stage;
import javafx.stage.StageStyle;
import javafx.stage.WindowEvent;
import net.sf.json.JSONObject;
import org.springframework.stereotype.Controller;

import javax.sound.sampled.Port;
import java.io.*;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @program: windowtest4
 * @description:
 * @author: liu yan
 * @create: 2024-10-23 14:18
 */
@Controller
public class managementController implements Initializable {

    @FXML
    public TableView<Routine> RoutineDataTable;
    @FXML
    public Button createButton;
    public TableView<wrenchRow> wrenchDataTable;
    public RadioButton taggerBtu;
    public TextField DBHost;
    public TextField DBPort;
    public TextField DBName;
    public TextField DBUser;
    public TextField DBPass;
    public TextField TableName;

    @FXML
    public Button test;
    public Label titState;


    private mainController mc;

    private ObservableList<Routine> data = FXCollections.observableArrayList();
    private ObservableList<wrenchRow> dataWrench = FXCollections.observableArrayList();

    private String configDirPath = System.getProperty("user.dir") + File.separator + "config" + File.separator;


    @Override
    public void initialize(URL url, ResourceBundle resourceBundle) {
        //初始化程序的数据表格
        CreateRoutineDataTable();
        //初始化扳手的数据表格
        CreateWrenchDataTable();

        // 设置按钮的点击事件监听器
        taggerBtu.setOnAction(this::taggerBtu);
//        createButton.setOnAction(this::handleCreateProgram);


    }

    private void CreateRoutineDataTable(){
        // 初始化表格列
        TableColumn<Routine, String> ID = new TableColumn<>("ID");
        ID.setCellValueFactory(new PropertyValueFactory<>("ID"));

        TableColumn<Routine, String> RoutineName = new TableColumn<>("程序名称");
        RoutineName.setCellValueFactory(new PropertyValueFactory<>("RoutineName"));

        TableColumn<Routine, Integer> BoltTypeNum = new TableColumn<>("螺栓数量");
        BoltTypeNum.setCellValueFactory(new PropertyValueFactory<>("BoltTypeNum"));

        TableColumn<Routine, String> addTime = new TableColumn<>("创建时间");
        addTime.setCellValueFactory(new PropertyValueFactory<>("addTime"));

        TableColumn<Routine, String> columnToHide = new TableColumn<>("螺栓内容");
        columnToHide.setCellValueFactory(new PropertyValueFactory<>("columnToHide"));
        columnToHide.setVisible(false);

        // 新增一个操作列
        TableColumn<Routine, Void> actionColumn = new TableColumn<>("操作");
        actionColumn.setPrefWidth(100); // 可根据需要设置列宽
        actionColumn.setCellFactory(column -> new TableCell<Routine, Void>() {
            @Override
            protected void updateItem(Void item, boolean empty) {
                super.updateItem(item, empty);

                if (empty || isEmpty()) { // 使用isEmpty()来检查单元格是否为空
                    setText(null);
                    setGraphic(null);
                } else {
                    HBox hbox = new HBox(10);
                    Button viewButton = new Button("编辑");
                    Button deleteButton = new Button("删除");
                    Button issueButton = new Button("下发");

                    // 设置按钮的尺寸
                    viewButton.setPrefWidth(53); // 设置首选宽度为100
                    viewButton.setMaxWidth(80);  // 设置最大宽度为200
                    viewButton.setMinWidth(40);   // 设置最小宽度为50
                    viewButton.setFont(new Font(11)); // 只指定大小，使用默认字体和样式

                    deleteButton.setPrefWidth(53); // 设置首选宽度为100
                    deleteButton.setMaxWidth(80);  // 设置最大宽度为200
                    deleteButton.setMinWidth(40);   // 设置最小宽度为50
                    deleteButton.setFont(new Font(11));

                    issueButton.setPrefWidth(53); // 设置首选宽度为100
                    issueButton.setMaxWidth(80);  // 设置最大宽度为200
                    issueButton.setMinWidth(40);   // 设置最小宽度为50
                    issueButton.setFont(new Font(11));

                    // 你也可以设置高度，如果需要的话
                    viewButton.setPrefHeight(20);
                    deleteButton.setPrefHeight(20);
                    issueButton.setPrefHeight(20);

                    viewButton.getStyleClass().add("edit-button-style");
                    deleteButton.getStyleClass().add("delete-button-style");
                    issueButton.getStyleClass().add("issue-button-style");

                    // 使用getTableRow().getItem()来获取当前行的数据
                    // 注意：这种方法在某些情况下可能不起作用，特别是当表格处于虚拟滚动时
                    final Routine currentRowItem = getTableRow() != null ? getTableRow().getItem() : null;

                    deleteButton.setOnAction(event -> {
                        if (currentRowItem != null) {
                            //删除程序
                            deleteRoutine(currentRowItem);
                            //删除任务列表中的程序
                            deleteTaskItemsForCode(currentRowItem);
                            //删除列表中的行
                            data.remove(currentRowItem);
                        }
                    });

                    viewButton.setOnAction(event -> {
                        if (currentRowItem != null) {
                            // 创建B页面的控制器和FXMLLoader
                            FXMLLoader loader = new FXMLLoader(getClass().getResource("/view/updateProgram.fxml"));
                            Parent bPageRoot = null;
                            try {
                                bPageRoot = loader.load();
                            } catch (IOException e) {
                                e.printStackTrace();
                            }
                            UpdateProgramController bController = loader.getController();
                            // 将数据传递给B页面的控制器
                            bController.setDataItem(currentRowItem);

                            // 创建一个新的Stage或Dialog来显示B页面
                            Stage stage = new Stage();
                            stage.initModality(Modality.APPLICATION_MODAL);
                            stage.initStyle(StageStyle.UTILITY);
                            stage.setTitle("编辑");
                            stage.setScene(new Scene(bPageRoot));
                            stage.showAndWait();
                            if(bController.isAdd()){
                                data.remove(currentRowItem);
                                Routine newData = bController.getNewData();
                                data.add(0,newData);
                            }
                        }
                    });

                    issueButton.setOnAction(event -> {
                        if (currentRowItem != null) {
                            // 创建B页面的控制器和FXMLLoader
                            FXMLLoader loader = new FXMLLoader(getClass().getResource("/view/issueRoutine.fxml"));
                            Parent bPageRoot = null;
                            try {
                                bPageRoot = loader.load();
                            } catch (IOException e) {
                                e.printStackTrace();
                            }
                            issueRoutineController bController = loader.getController();
                            // 将数据传递给B页面的控制器

                            bController.setDataItem(currentRowItem,mc);

                            // 创建一个新的Stage或Dialog来显示B页面
                            Stage stage = new Stage();
                            stage.initModality(Modality.APPLICATION_MODAL);
                            stage.initStyle(StageStyle.UTILITY);
                            stage.setTitle("选择扳手");
                            stage.setScene(new Scene(bPageRoot));
                            stage.showAndWait();
//                            if(bController.isAdd()){
//                                data.remove(currentRowItem);
//                                Routine newData = bController.getNewData();
//                                data.add(0,newData);
//                            }
                        }
                    });

                    hbox.getChildren().addAll(viewButton,deleteButton,issueButton);
                    setGraphic(hbox);
                }
            }
        });


        // 读取文件并填充数据
        try {
            InputStream inputStream = new FileInputStream(configDirPath+"Routine.txt");
            if(inputStream == null){
                System.err.println("未找到系统文件：Routine.txt");
            }
            BufferedReader br = new BufferedReader(new InputStreamReader(inputStream));
            String line;
            String currentLine = null;
//            if(br.readLine()!=null && br.readLine().length()>0){
                while ((line = br.readLine()) != null) {
                    currentLine = line;
                    if (currentLine!= null && currentLine.length() > 0) {
                        JSONObject js= JSONObject.fromObject(line);

                        Routine row = new Routine(
                                js.get("code").toString(),
                                js.getString("RoutineName"),
                                Integer.parseInt(js.getString("TorqueNum")),
                                js.getString("addTime"),
                                js.getString("content")
                        );
                        data.add(row);
                    }
                }
//            }

        } catch (IOException e) {
            e.printStackTrace();
            // 处理异常，例如显示错误消息
        }


        // 将列添加到表格中
        RoutineDataTable.getColumns().addAll(ID, RoutineName, BoltTypeNum,addTime,actionColumn);

        // 初始化逻辑
        // 设置表格的项为data列表
        RoutineDataTable.setItems(data);
    }

    private void CreateWrenchDataTable(){
        // 初始化表格列
        TableColumn<wrenchRow, String> SN = new TableColumn<>("SN");
        SN.setCellValueFactory(new PropertyValueFactory<>("SN"));

        TableColumn<wrenchRow, String> TorqueName = new TableColumn<>("扳手名称");
        TorqueName.setCellValueFactory(new PropertyValueFactory<>("TorqueName"));

        TableColumn<wrenchRow, Double> TorqueMin = new TableColumn<>("最小扭矩");
        TorqueMin.setCellValueFactory(new PropertyValueFactory<>("TorqueMin"));

        TableColumn<wrenchRow, Double> TorqueMax = new TableColumn<>("最大扭矩");
        TorqueMax.setCellValueFactory(new PropertyValueFactory<>("TorqueMax"));

        TableColumn<wrenchRow, String> SSID = new TableColumn<>("SSID");
        SSID.setCellValueFactory(new PropertyValueFactory<>("SSID"));

        TableColumn<wrenchRow, String> password = new TableColumn<>("Wi-Fi密码");
        password.setCellValueFactory(new PropertyValueFactory<>("password"));

        TableColumn<wrenchRow, String> Host = new TableColumn<>("IP地址");
        Host.setCellValueFactory(new PropertyValueFactory<>("Host"));

        TableColumn<wrenchRow, Integer> Port = new TableColumn<>("端口");
        Port.setCellValueFactory(new PropertyValueFactory<>("Port"));

        TableColumn<wrenchRow, String> SubnetMask = new TableColumn<>("子网掩码");
        SubnetMask.setCellValueFactory(new PropertyValueFactory<>("SubnetMask"));

        TableColumn<wrenchRow, String> gateway = new TableColumn<>("子网掩码");
        gateway.setCellValueFactory(new PropertyValueFactory<>("gateway"));

        TableColumn<wrenchRow, String> addTime = new TableColumn<>("添加时间");
        addTime.setCellValueFactory(new PropertyValueFactory<>("addTime"));


        // 新增一个操作列
        TableColumn<wrenchRow, Void> actionColumn = new TableColumn<>("操作");
        actionColumn.setPrefWidth(100); // 可根据需要设置列宽
        actionColumn.setCellFactory(column -> new TableCell<wrenchRow, Void>() {
            @Override
            protected void updateItem(Void item, boolean empty) {
                super.updateItem(item, empty);

                if (empty || isEmpty()) { // 使用isEmpty()来检查单元格是否为空
                    setText(null);
                    setGraphic(null);
                } else {
                    HBox hbox = new HBox(10);
                    Button viewButton = new Button("编辑");
                    Button deleteButton = new Button("删除");

                    // 设置按钮的尺寸
                    viewButton.setPrefWidth(53); // 设置首选宽度为100
                    viewButton.setMaxWidth(80);  // 设置最大宽度为200
                    viewButton.setMinWidth(40);   // 设置最小宽度为50
                    viewButton.setFont(new Font(11)); // 只指定大小，使用默认字体和样式

                    deleteButton.setPrefWidth(53); // 设置首选宽度为100
                    deleteButton.setMaxWidth(80);  // 设置最大宽度为200
                    deleteButton.setMinWidth(40);   // 设置最小宽度为50
                    deleteButton.setFont(new Font(11));

                    // 你也可以设置高度，如果需要的话
                    viewButton.setPrefHeight(20);
                    deleteButton.setPrefHeight(20);

                    viewButton.getStyleClass().add("edit-button-style");
                    deleteButton.getStyleClass().add("delete-button-style");

                    // 使用getTableRow().getItem()来获取当前行的数据
                    // 注意：这种方法在某些情况下可能不起作用，特别是当表格处于虚拟滚动时
                    final wrenchRow currentRowItem = getTableRow() != null ? getTableRow().getItem() : null;

                    deleteButton.setOnAction(event -> {
                        if (currentRowItem != null) {
                            //删除扳手
                            handleDeleteWrench(currentRowItem);
                            //删除扳手的任务信息
                            handleDeleteWrenchForTaskItems(currentRowItem);
                            //删除列表中的行
                            dataWrench.remove(currentRowItem);
                        }
                    });

                    viewButton.setOnAction(event -> {
                        if (currentRowItem != null) {
                            // 创建B页面的控制器和FXMLLoader
                            FXMLLoader loader = new FXMLLoader(getClass().getResource("/view/wrench/updateWrench.fxml"));
                            Parent bPageRoot = null;
                            try {
                                bPageRoot = loader.load();
                            } catch (IOException e) {
                                e.printStackTrace();
                            }
                            updateWrenchController bController = loader.getController();
//                             将数据传递给B页面的控制器
                            bController.setDataItem(currentRowItem);

                            // 创建一个新的Stage或Dialog来显示B页面
                            Stage stage = new Stage();
                            stage.initModality(Modality.APPLICATION_MODAL);
                            stage.initStyle(StageStyle.UTILITY);
                            stage.setTitle("编辑");
                            stage.setScene(new Scene(bPageRoot));
                            stage.showAndWait();
                            if(bController.isAdd()){
                                dataWrench.remove(currentRowItem);
                                wrenchRow newData = bController.getNewData();
                                dataWrench.add(0,newData);
                            }
                        }
                    });


                    hbox.getChildren().addAll(viewButton,deleteButton);
                    setGraphic(hbox);
                }
            }
        });


        // 读取文件并填充数据
        try {
            InputStream inputStream = new FileInputStream(configDirPath+"torqueItems.txt");
            if(inputStream == null){
                System.err.println("未找到系统文件：torqueItems.txt");
            }
            BufferedReader br = new BufferedReader(new InputStreamReader(inputStream));
            String line;
            String currentLine = null;
            while ((line = br.readLine()) != null) {
                currentLine = line;
                if (currentLine!= null && currentLine.length() > 0) {
                    JSONObject js= JSONObject.fromObject(line);

                    wrenchRow row = new wrenchRow(
                            js.get("SN").toString(),
                            js.getString("TorqueName"),
                            Double.parseDouble(js.getString("TorqueMin")),
                            Double.parseDouble(js.getString("TorqueMax")),
                            js.getString("SSID"),
                            js.getString("password"),
                            js.getString("Host"),
                            Integer.parseInt(js.getString("Port")),
                            js.getString("SubnetMask"),
                            js.getString("gateway"),
                            js.getString("addTime")
                    );
                    dataWrench.add(row);
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
            // 处理异常，例如显示错误消息
        }

        // 将列添加到表格中
        wrenchDataTable.getColumns().addAll(SN, TorqueName, TorqueMin, TorqueMax, Host, Port, addTime, actionColumn);

        // 初始化逻辑
        // 设置表格的项为data列表
        wrenchDataTable.setItems(dataWrench);
    }

    // 删除程序
    private void deleteRoutine(Routine routine) {
        String filePath = configDirPath+"Routine.txt"; // 您可以根据需要更改文件路径
        String tempFilePath = filePath + ".tmp";
        String targetCode = routine.getID();

//                            InputStream inputStream = new FileInputStream(configDirPath+filePath); managementController.class.getClassLoader().getResourceAsStream(filePath);

        List<String> lines = new ArrayList<>();
        try (InputStream inputStream = new FileInputStream(filePath);
             BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, StandardCharsets.UTF_8))) {
            String line;
            while ((line = reader.readLine())!= null) {
                lines.add(line);
            }
        } catch (IOException e) {
            System.err.println("读取文件错误："+e);
        }

        // 查找并删除目标行
        Iterator<String> iterator = lines.iterator();
        boolean deleted = false;
        while (iterator.hasNext()) {
            String line = iterator.next();
            if (line.contains("\"code\":\"" + targetCode + "\"")) {
                iterator.remove();
                deleted = true;
                break; // 如果只需要删除第一处匹配，就跳出循环
            }
        }

        if (!deleted) {
            System.out.println("未找到code为" + targetCode + "的行。");
            return;
        }

        // 将修改后的内容写回临时文件
        try (BufferedWriter writer = new BufferedWriter(new FileWriter(tempFilePath))) {
            for (String line : lines) {
                writer.write(line);
                writer.newLine();
            }
        } catch (IOException e) {
            e.printStackTrace();
            return;
        }

        // 替换原始文件
        try {
            Files.deleteIfExists(Paths.get(filePath));
            Files.move(Paths.get(tempFilePath), Paths.get(filePath), StandardCopyOption.REPLACE_EXISTING);
            System.out.println("文件删除成功！");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    //删除任务列表中的程序
    private void deleteTaskItemsForCode(Routine routine){
        String filePath = configDirPath+"taskItems.txt"; // 文件路径
        String tempFilePath = filePath + ".tmp";
        String targetCode = routine.getID();

        List<String> lines = new ArrayList<>();
        try (InputStream inputStream = new FileInputStream(filePath);
             BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, StandardCharsets.UTF_8))) {
            String line;
            while ((line = reader.readLine())!= null) {
                lines.add(line);
            }
        } catch (IOException e) {
            System.err.println("读取文件错误："+e);
        }

        // 查找并删除目标行
        Iterator<String> iterator = lines.iterator();
        boolean deleted = false;
        while (iterator.hasNext()) {
            String line = iterator.next();
            if (line.contains("\"RoutineId\":\"" + targetCode + "\"")) {
                iterator.remove();
                deleted = true;
                break; // 如果只需要删除第一处匹配，就跳出循环
            }
        }

        if (!deleted) {
            System.out.println("未找到code为" + targetCode + "的行。");
            return;
        }

        // 将修改后的内容写回临时文件
        try (BufferedWriter writer = new BufferedWriter(new FileWriter(tempFilePath))) {
            for (String line : lines) {
                writer.write(line);
                writer.newLine();
            }
        } catch (IOException e) {
            e.printStackTrace();
            return;
        }

        // 替换原始文件
        try {
            Files.deleteIfExists(Paths.get(filePath));
            Files.move(Paths.get(tempFilePath), Paths.get(filePath), StandardCopyOption.REPLACE_EXISTING);
            System.out.println("文件删除成功！");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @FXML
    private void handleCreateProgram() {
        try {
            // 加载FXML文件
            FXMLLoader loader = new FXMLLoader(getClass().getResource("/view/createProgram.fxml"));
            VBox vbox = loader.load();

            // 获取控制器（如果需要）
            // CreateProgramController controller = loader.getController();
             createProgramController controller = loader.getController();


            // 创建新窗口
            Stage formStage = new Stage();
            formStage.initModality(Modality.APPLICATION_MODAL);
            formStage.initStyle(StageStyle.UTILITY);
            formStage.setTitle("创建程序");

//            // 设置新窗口的场景
            Scene formScene = new Scene(vbox); // 调整大小以适应内容
            formStage.setScene(formScene);
            formStage.showAndWait(); // 显示窗口并等待其关闭
            if(controller.isAdd()){
                Routine newData = controller.getNewData();
                data.add(newData);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @FXML
    private void handleCreateWrench() {
        // 实现创建扳手的逻辑
        try {
            // 加载FXML文件
            FXMLLoader loader = new FXMLLoader(getClass().getResource("/view/wrench/createWrench.fxml"));
            AnchorPane vbox = loader.load();

            // 获取控制器（如果需要）
            createWrenchController controller = loader.getController();


            // 创建新窗口
            Stage formStage = new Stage();
            formStage.initModality(Modality.APPLICATION_MODAL);
            formStage.initStyle(StageStyle.UTILITY);
            formStage.setTitle("添加扳手");

//            // 设置新窗口的场景
            Scene formScene = new Scene(vbox); // 调整大小以适应内容
            formStage.setScene(formScene);
            formStage.showAndWait(); // 显示窗口并等待其关闭
            if(controller.isAdd()){
                wrenchRow newData = controller.getNewData();
                dataWrench.add(newData);
                this.mc.addWrenchList(newData.getSN(), newData.getHost(), newData.getPort());
//                System.out.println("你好："+this.mc+"   是否唯恐："+this.mc==null);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @FXML
    private void handleViewWrench() {
        // 实现查看扳手的逻辑
    }

    //删除扳手信息
    private void handleDeleteWrench(wrenchRow wrenchRow) {
        // 实现删除扳手的逻辑
        String filePath = configDirPath+"torqueItems.txt"; // 您可以根据需要更改文件路径
        String tempFilePath = filePath + ".tmp";
        String targetCode = wrenchRow.getSN();

        List<String> lines = new ArrayList<>();
        try (InputStream inputStream = new FileInputStream(filePath);
             BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, StandardCharsets.UTF_8))) {
            String line;
            while ((line = reader.readLine())!= null) {
                lines.add(line);
            }
        } catch (IOException e) {
            System.err.println("读取文件错误："+e);
        }

        // 查找并删除目标行
        Iterator<String> iterator = lines.iterator();
        boolean deleted = false;
        while (iterator.hasNext()) {
            String line = iterator.next();
            if (line.contains("\"SN\":\"" + targetCode + "\"")) {
                iterator.remove();
                deleted = true;
                break; // 如果只需要删除第一处匹配，就跳出循环
            }
        }

        if (!deleted) {
            System.out.println("未找到code为" + targetCode + "的行。");
            return;
        }

        // 将修改后的内容写回临时文件
        try (BufferedWriter writer = new BufferedWriter(new FileWriter(tempFilePath))) {
            for (String line : lines) {
                writer.write(line);
                writer.newLine();
            }
        } catch (IOException e) {
            e.printStackTrace();
            return;
        }

        // 替换原始文件
        try {
            Files.deleteIfExists(Paths.get(filePath));
            Files.move(Paths.get(tempFilePath), Paths.get(filePath), StandardCopyOption.REPLACE_EXISTING);
            System.out.println("文件删除成功！");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    //删除扳手任务信息
    private void handleDeleteWrenchForTaskItems(wrenchRow wrenchRow){
        String filePath = configDirPath+"taskItems.txt"; // 您可以根据需要更改文件路径
        String tempFilePath = filePath + ".tmp";
        String targetCode = wrenchRow.getSN();

        List<String> lines = new ArrayList<>();
        try (InputStream inputStream = new FileInputStream(filePath);
             BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, StandardCharsets.UTF_8))) {
            String line;
            while ((line = reader.readLine())!= null) {
                lines.add(line);
            }
        } catch (IOException e) {
            System.err.println("读取文件错误："+e);
        }

        // 查找并删除目标行
        Iterator<String> iterator = lines.iterator();
        boolean deleted = false;
        while (iterator.hasNext()) {
            String line = iterator.next();
            if (line.contains("\"SN\":\"" + targetCode + "\"")) {
                iterator.remove();
                deleted = true;
                break; // 如果只需要删除第一处匹配，就跳出循环
            }
        }
        this.mc.removeWrenchTask(targetCode);

        if (!deleted) {
            System.out.println("未找到code为" + targetCode + "的行。");
            return;
        }

        // 将修改后的内容写回临时文件
        try (BufferedWriter writer = new BufferedWriter(new FileWriter(tempFilePath))) {
            for (String line : lines) {
                writer.write(line);
                writer.newLine();
            }
        } catch (IOException e) {
            e.printStackTrace();
            return;
        }

        // 替换原始文件
        try {
            Files.deleteIfExists(Paths.get(filePath));
            Files.move(Paths.get(tempFilePath), Paths.get(filePath), StandardCopyOption.REPLACE_EXISTING);
            System.out.println("文件删除成功！");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void setDataItem(mainController mc) {
        this.mc=mc;
        if(mc.getDbstate().equals("true")){
            titState.setText("开启");
            taggerBtu.setText("开启");
            taggerBtu.setSelected(true);
        }else{
            titState.setText("关闭");
            taggerBtu.setText("关闭");
            taggerBtu.setSelected(false);
        }

        System.out.println("数据库URL:"+mc.getDbUrl());
        String [] dbUrlarr=mc.getDbUrl().split(";");
        DBHost.setText(dbUrlarr[0].split(":")[2].substring(2));
        DBName.setText(dbUrlarr[1].split("=")[1]);
        DBPort.setText(dbUrlarr[0].split(":")[3]);
        DBUser.setText(mc.getDbUser());
        DBPass.setText(mc.getDbPass());
        TableName.setText(mc.getDbTable());
    }

    @FXML
    public void taggerBtu(ActionEvent actionEvent) {
        if (taggerBtu.isSelected()) {
            taggerBtu.setText("开启");
        } else {
            taggerBtu.setText("关闭");
        }
    }

    private static final String CONFIG_FILE_PATH = System.getProperty("user.dir") + File.separator + "config" + File.separator+ "application.properties"; // 配置文件路径
    private static final String CORRECT_DBState = "correct.DBstate"; // 配置文件中的数据库连接属性
    private static final String DBUSER = "spring.datasource.username";
    private static final String DBPASS = "spring.datasource.password";
    private static final String DBURL = "spring.datasource.url";
    private static final String TABLENAME = "correct.TABLEName";

    public void SaveDB(ActionEvent actionEvent) {
        boolean DBState=taggerBtu.isSelected();
        String dbHost=DBHost.getText();
        String dbPort=DBPort.getText();
        String dbName=DBName.getText();
        String dbUser=DBUser.getText();
        String dbPass=DBPass.getText();
        String tableName=TableName.getText();

        boolean isValid = true;

        isValid &= !isTextFieldEmptyOrWhitespace(DBHost, "主机不能为空");
        isValid &= !isTextFieldEmptyOrWhitespace(DBPort, "端口不能为空");
        isValid &= !isTextFieldEmptyOrWhitespace(DBName, "数据库名称不能为空");
        isValid &= !isTextFieldEmptyOrWhitespace(DBUser, "用户不能为空");
        isValid &= !isTextFieldEmptyOrWhitespace(DBPass, "密码不能为空");
        isValid &= !isTextFieldEmptyOrWhitespace(TableName, "表名不能为空");

        if (isValid) {
            String dbUrl="jdbc:sqlserver://"+dbHost+":"+dbPort+";databaseName="+dbName;
            //修改数据库配置
            updateConfig(DBState,dbUrl,dbUser,dbPass,tableName);
            showAlert(Alert.AlertType.INFORMATION,"保存成功",null,"数据库信息保存成功，系统重启后生效");
        }
    }

    //更新配置文件中的数据库连接信息
    private void updateConfig(boolean DBState,String DBUrl,String DBUser,String DBPass,String TableName) {
        Properties properties = new Properties();
        try (InputStream input = new FileInputStream(CONFIG_FILE_PATH)) {
            // 从配置文件中加载属性
            properties.load(input);
        } catch (IOException ex) {
            ex.printStackTrace();
            // 处理文件读取异常，例如显示错误消息等
            return;
        }
        // 更新数据库属性
        properties.setProperty(CORRECT_DBState, Boolean.toString(DBState));
        properties.setProperty(DBUSER, DBUser);
        properties.setProperty(DBPASS, DBPass);
        properties.setProperty(DBURL, DBUrl);
        properties.setProperty(TABLENAME, TableName);

        try (OutputStream output = new FileOutputStream(CONFIG_FILE_PATH)) {
            // 将更新后的属性写回配置文件
            properties.store(output, null);
        } catch (IOException ex) {
            ex.printStackTrace();
            // 处理文件写入异常，例如显示错误消息等
        }
    }

    private boolean isTextFieldEmptyOrWhitespace(TextField textField, String errorMessage) {
        String text = textField.getText().trim();
        if (text.isEmpty()) {
            showAlert(Alert.AlertType.ERROR,"验证错误", "请填写所有必填项",errorMessage);
            System.err.println(errorMessage);
            return true;
        }
        return false;
    }

    private void showAlert(Alert.AlertType alertType, String title, String headerText,String ContentText) {
        Alert alert = new Alert(alertType);
        alert.setTitle(title);
        alert.setHeaderText(headerText);
        alert.setContentText(ContentText); // 可以根据需要自定义内容文本
        alert.showAndWait(); // 显示对话框并等待用户响应
    }
}
